package me.maiz.tool.codemonitor.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import me.maiz.tool.codemonitor.common.DateUtil;
import me.maiz.tool.codemonitor.dal.CommitRepo;
import me.maiz.tool.codemonitor.dal.RawDataRepo;
import me.maiz.tool.codemonitor.dal.StudentRepo;
import me.maiz.tool.codemonitor.entity.*;
import me.maiz.tool.codemonitor.service.StudentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

@RestController
@RequestMapping("push")
@Slf4j
public class PushHookController {
    @Autowired
    private RawDataRepo rawDataRepo;
    @Autowired
    private CommitRepo commitRepo;

    @Autowired
    private StudentRepo studentRepo;

    @Autowired
    private ObjectMapper objectMapper;

    @PostMapping("receive")
    public String receive(HttpServletRequest request, @RequestBody String payload) {
        log.info("payload:" + payload);

        RawData rawData = new RawData();
        rawData.setData(payload);
        rawData.setReceivedTime(new Date());
        rawDataRepo.save(rawData);

        try {
            GiteeWebHookData giteeWebHookData = objectMapper.readValue(payload, GiteeWebHookData.class);

            List<Commits> commits = giteeWebHookData.getCommits();
            for (Commits commit : commits) {
                CommitDO commitDO = new CommitDO();
                BeanUtils.copyProperties(commit, commitDO, "author", "added", "removed", "modified");
                Author author = commit.getAuthor();
                commitDO.setAuthor(author.getName());
                commitDO.setEmail(author.getEmail());

                commitDO.setRepository(giteeWebHookData.getRepository().getName());
                commitDO.setRepositoryUrl(giteeWebHookData.getRepository().getUrl());

                Student student = studentRepo.findByEmailOrGiteeUsername(author.getEmail(), author.getName());
                log.info("学生信息：{}",student);
                commitDO.setRealName(student!=null?student.getName():"");
                writeList(commit.getAdded(), commitDO);
                writeList(commit.getRemoved(), commitDO);
                writeList(commit.getModified(), commitDO);

                commitRepo.save(commitDO);
                if(student!=null) {
                    //换天算法，如果本次提交时间和上次提交时间是同一天，则累加，否则认为是新一天初始为1
                    if(student.getLastCommitTime()!=null&&DateUtil.isSameDay(commit.getTimestamp(),student.getLastCommitTime())) {
                        log.info("{}与{}是同一天",commit.getTimestamp(),student.getLastCommitTime());
                        student.setDailyCommitCount(student.getDailyCommitCount() + 1);
                    }else{
                        student.setDailyCommitCount(1);
                    }
                    student.setTotalCommitCount(student.getTotalCommitCount() + 1);
                    student.setLastCommit(commit.getUrl());
                    student.setLastCommitTime(commit.getTimestamp());
                    studentRepo.save(student);
                }else{
                    log.warn("未录入用户{}:{}的真实姓名",author.getEmail(),author.getUsername());
                }
            }



            log.info("接收通知成功~");
        } catch (JsonProcessingException e) {
            log.warn("解析json出错", e);
        }

        return "success";
    }


    private void writeList(List<String> list, CommitDO commitDO) throws JsonProcessingException {
        if (!list.isEmpty()) {
            commitDO.setAdded(objectMapper.writeValueAsString(list));
        }
    }

    @GetMapping("echo")
    public String test(HttpServletRequest request) {
        return request.getRemoteAddr();
    }

}
